package com.yunxun.coinmessage.service;

import com.yunxun.coinmessage.dao.AdministratorDao;
import com.yunxun.coinmessage.entity.Administrator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

@Service
public class AdministratorService {
    @Autowired
    AdministratorDao administratorDao;
    public  Integer add(Administrator administrator){
        //给密码进行md5加密
        String md5Password=getMd5Password(administrator.getApassword());
        administrator.setApassword(md5Password);

       return administratorDao.add(administrator);
    }
    public Administrator queryAdministrator(String aname,String apassword){
        //将密码转化成MD5
        String md5Password=getMd5Password(apassword);
        apassword=md5Password;
       return administratorDao.queryAdministrator(aname,apassword);
    }

    public  String getMd5Password(String password) {
        try {
            // 得到一个信息摘要器
            MessageDigest digest = MessageDigest.getInstance("md5");
            byte[] result = digest.digest(password.getBytes());
            StringBuffer buffer = new StringBuffer();
            // 把每一个byte 做一个与运算 0xff;
            for (byte b : result) {
                // 与运算
                int number = b & 0xff;// 加盐
                String str = Integer.toHexString(number);
                if (str.length() == 1) {
                    buffer.append("0");
                }
                buffer.append(str);
            }

            // 标准的md5加密后的结果
            return buffer.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return "";
        }

    }
}
